import 'dart:io';

import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/model/upload_result_entity.dart';
import 'package:tender_flutter/page/home/model/user_info_entity.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/img_picker.dart';
import 'package:tender_flutter/utils/picker.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/net_image.dart';

class PersonInfoPage extends StatefulWidget {
  @override
  _PersonInfoPageState createState() => _PersonInfoPageState();
}

class _PersonInfoPageState extends State<PersonInfoPage> {
  TextEditingController sexController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  TextEditingController companyController = TextEditingController();

  // /// 用户信息状态管理
  // var profileProvider;

  /// 选择的本地图片文件
  File portraitImgFile;

  /// 上传到服务端之后的url
  String portraitUrl;

  /// 城市选择code
  int _cityCode;

  /// 性别 1男 2女
  int sex;

  /// 获取用户信息
  Future _getUserInfo() async {
    var response = await ApiPerson.getUserInfo<UserInfoEntity>();
    UserInfoEntity infoEntity = response.result;
    portraitUrl = infoEntity.picture;
    _cityCode = int.parse(infoEntity.areaId ?? "0");
    sex = (infoEntity.sex ?? "男") == "男" ? 1 : 2;
    phoneController.text = infoEntity.phone;
    addressController.text = infoEntity.area;
    companyController.text = infoEntity.company;
    sexController.text = infoEntity.sex ?? "男";

    setState(() {});
  }

  /// 更新用户信息
  Future _updateUserInfo() async {
    /// 上传图片
    List<Future> uploadApis = [];
    if (portraitImgFile != null) {
      uploadApis.add(_uploadImage(portraitImgFile)
          .then((value) => portraitUrl = value.url));
    }

    Future.wait(uploadApis).then((value) {
      ApiPerson.updateUserInfo(
              areaCode: _cityCode,
              company: companyController.text,
              phone: phoneController.text,
              avator: portraitUrl,
              sex: sex)
          .then((value) =>
              {ToastUtils.show("更新成功"), LRouter.navigatorCtx(context).pop()});
    }).catchError((e) {
      ToastUtils.show("头像资源上传失败");
    });
  }

  /// 上传图片
  Future _uploadImage(File file) async {
    ApiResponse<UploadResultEntity> response =
        await ApiCommon.uploadImage([file]);
    return response.result;
  }

  @override
  void initState() {
    super.initState();

    /// 页面渲染完成之后的回调，只执行一次
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      _getUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    // profileProvider = Store.of<UserProfileInfo>(context);
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("基本信息", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return SingleChildScrollView(
      child: Container(
        child: Column(
          children: [_initList(), _initExitBtn()],
        ),
      ),
    );
  }

  /// 列表
  Widget _initList() {
    List<Widget> cells = [
      _getPortraitlCell("设置头像", () {
        ImagePickerUtils.getImage(PICKER_PHOTO).then((value) {
          setState(() {
            portraitImgFile = value;
          });
        });
      }),
      _getOptionCell("性别", "请选择性别", sexController, () {
        PickerUtils.showStringPicker(context, data: ["男", "女"],
            clickCallBack: (index, value) {
          sexController.text = value;
          sex = (sexController.text == "男" ? 1 : 2);
        });
      }),
      _getDetailCell("手机号", "请输入手机号码", phoneController),
      _getOptionCell("所在区域", "请选择区域", addressController, () {
        PickerUtils.showCityPicker(context, clickCallBack: (codes, value) {
          _cityCode = codes.last;
          addressController.text = value;
        });
      }),
      _getDetailCell("企业名称", "请输入公司名称", companyController),
    ];

    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: cells.length,
      itemBuilder: (BuildContext context, int index) {
        return cells[index];
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          color: ThemeColors.colorType25,
        );
      },
    );
  }

  /// 保存按钮
  Widget _initExitBtn() {
    return Container(
      margin: EdgeInsets.only(
          top: ScreenAdapter.height(200),
          left: ScreenAdapter.width(30),
          right: ScreenAdapter.width(30)),
      width: double.infinity,
      height: ScreenAdapter.height(90),
      child: FlatButton(
        color: ThemeColors.colorType6,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(ScreenAdapter.width(14)),
        ),
        child: Text(
          "保存",
          style: TextStyle(
              color: ThemeColors.colorWhite, fontSize: ScreenAdapter.sp(28)),
        ),
        onPressed: () {
          _updateUserInfo();
        },
      ),
    );
  }

  /// 头像cell
  Widget _getPortraitlCell(String text, GestureTapCallback callback) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenAdapter.width(30),
          right: ScreenAdapter.width(30),
          top: ScreenAdapter.height(15),
          bottom: ScreenAdapter.height(15)),
      child: Row(
        children: <Widget>[
          // SizedBox(height: ScreenAdapter.width(15)),
          Text(text,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(28))),
          Expanded(child: SizedBox()),
          GestureDetector(
              onTap: callback,
              child: portraitImgFile != null
                  ? ClipOval(
                      child: Image.file(portraitImgFile,
                          fit: BoxFit.cover,
                          width: ScreenAdapter.width(100),
                          height: ScreenAdapter.width(100)),
                    )
                  : MyNetImage(
                      width: ScreenAdapter.width(100),
                      height: ScreenAdapter.width(100),
                      url: portraitUrl ?? "",
                      radius: BorderRadius.circular(ScreenAdapter.width(50)),
                      placeholder: Image.asset(
                          RPath.imgPath + "img_portait_placeholder.png"),
                      imageClickAction: (state) {
                        callback();
                      }))
        ],
      ),
    );
  }

  /// 选择类型cell
  Widget _getOptionCell(String text, String placeholder,
      TextEditingController controller, GestureTapCallback callback) {
    return Container(
      height: ScreenAdapter.height(70),
      padding: EdgeInsets.only(
          left: ScreenAdapter.width(30), right: ScreenAdapter.width(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          // SizedBox(height: ScreenAdapter.width(15)),
          Text(text,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(28))),
          // Expanded(child: SizedBox()),

          Expanded(
              child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
            SizedBox(
                width: ScreenAdapter.width(500),
                child: TextField(
                  onTap: callback,
                  decoration: InputDecoration(
                    hintText: placeholder,
                    focusedBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    disabledBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    enabledBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    border: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    contentPadding: EdgeInsets.symmetric(vertical: 0),
                  ),
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(26)),
                  textAlign: TextAlign.right,
                  maxLines: 1,
                  // enabled: false,
                  readOnly: true,
                  autofocus: false,
                  controller: controller,
                )),
            Image.asset(
              RPath.imgPath + "icon_person_right_arrow.png",
              fit: BoxFit.contain,
              width: ScreenAdapter.width(25),
              height: ScreenAdapter.width(25),
            )
          ]))
        ],
      ),
    );
  }

  /// 子标题cell
  Widget _getDetailCell(
      String text, String placeholder, TextEditingController controller) {
    return Container(
      // height: MediaQuery.of(context).size.width / 4,
      // margin: EdgeInsets.only(
      //     top: ScreenAdapter.height(20), bottom: ScreenAdapter.height(20)),
      height: ScreenAdapter.height(80),
      padding: EdgeInsets.only(
          left: ScreenAdapter.width(30), right: ScreenAdapter.width(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          // SizedBox(height: ScreenAdapter.width(15)),
          Text(text,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(28))),
          Expanded(child: SizedBox()),
          Expanded(
            child: TextField(
              decoration: InputDecoration(
                  hintText: placeholder, border: InputBorder.none),
              controller: controller,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(26)),
              textAlign: TextAlign.right,
              maxLines: 1,
            ),
          )
        ],
      ),
    );
  }
}
